<script setup lang="ts">
import { nextTick, ref } from 'vue'
import { Edit, Refresh } from '@element-plus/icons-vue'
import mittBus from '@/utils/mitt'
import { ElMessage } from 'element-plus'
import { getColumnTips } from '@/utils/custom'
import type { BaseFormRow, BusinessUIFormType, BusinessUITableType, DicType } from '@/types/custom'

import TemplateForm from '@/views/components/form/TemplateForm.vue'

interface Props {
  modal?: boolean
  disabled?: boolean
  params?: TypedAny
}

defineProps<Props>()

const formRef = ref()
const fullscreen = ref(false)
const loading = ref(false)
const dialogVisible = ref(false)
// 表单
const uiForm = ref<BusinessUIFormType | undefined>()
// 表格
const uiTable = ref<BusinessUITableType | undefined>()
// 表单字典
const dicTable = ref<DicType[]>([])
// 表单ID
const formId = ref('')
// 表单模式
const isForm = ref(false)
// row
const row = ref<TypedAny>({})

/**
 * 回调函数（用于保存后执行的函数）
 */
let callback = () => {}

/**
 * 提交数据
 * @param isClose
 */
const submitForm = (isClose?: boolean) => {
  loading.value = true
  formRef.value
    .submitForm()
    .then(({ data }: any) => {
      if (data && data.forms && data.forms.length) {
        // 把数据广播给表单
        mittBus.emit('onUpdateParent', data)
      }
      if (isClose) {
        dialogVisible.value = false
      } else if (data && data.id) {
        row.value = data
        formId.value = data.id
        onFetchForm()
      }
      callback()
      ElMessage.success('保存成功')
    })
    .finally(() => (loading.value = false))
}

/**
 * 加载中
 */
const onFetchForm = () => {
  nextTick(() => {
    loading.value = true
    formRef.value.onFetch().then(() => {
      loading.value = false
    })
  })
}

const open = async (option: BaseFormRow) => {
  if (option.uiForm) {
    uiForm.value = option.uiForm
    fullscreen.value = option.uiForm.items.some((s) => ['custom-business'].includes(s.component))
  }

  formId.value = option.row ? option.row.id : ''
  isForm.value = !!option.isForm

  if (option.row) row.value = option.row
  if (option.uiTable) uiTable.value = option.uiTable
  if (option.dicTable) dicTable.value = option.dicTable
  if (option.onFetch) callback = option.onFetch
  dialogVisible.value = true

  onFetchForm()
}

defineExpose({ open })
</script>

<template>
  <div>
    <vxe-modal
      show-zoom
      :show-minimize="false"
      :dblclick-zoom="false"
      :fullscreen="fullscreen"
      resize
      v-model="dialogVisible"
      width="80%"
      height="80%"
      destroy-on-close
      class-name="custom-modal"
    >
      <template #title>
        <div class="flex align-center flex-grow" v-if="isForm">
          <el-button
            type="primary"
            @click="submitForm()"
            :loading="loading"
            :icon="Edit"
            v-if="!disabled"
          >
            保存
          </el-button>
          <el-button
            type="warning"
            @click="submitForm(true)"
            :loading="loading"
            :icon="Edit"
            v-if="!disabled"
            class="ml5"
          >
            保存并关闭
          </el-button>
          <el-button
            @click="onFetchForm"
            :loading="loading"
            :icon="Refresh"
            class="ml5"
            v-if="formId"
          >
            刷新
          </el-button>
          <el-button @click="dialogVisible = false" class="ml5">关闭</el-button>
          <!--        <span class="ml-auto font16 mr10">{{ title }}</span>-->
        </div>
        <div class="flex align-center flex-grow font-bold" v-else>
          <el-button @click="dialogVisible = false">关闭</el-button>
          <span class="ml5">{{ getColumnTips(uiTable?.columns || [], row) }}</span>
        </div>
      </template>
      <div class="h100 flex flex-column pa10">
        <TemplateForm
          ref="formRef"
          :is-form="isForm"
          v-model="formId"
          :params="params"
          :ui-form="uiForm"
          :ui-table="uiTable"
          :dic-table="dicTable"
          :disabled="disabled"
        />
      </div>
    </vxe-modal>
  </div>
</template>
